package de.suur.jarmi.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavaSerializer implements Serializer {

	private static final transient Logger log = LoggerFactory
			.getLogger(JavaSerializer.class);

	public <T extends Serializable> T deserialize(byte[] data) {
		try {
			log.trace("Deserialize: " + data.length + "|"
					+ JarmiUtil.toString(data));
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ByteArrayInputStream bis = new ByteArrayInputStream(data);
			ObjectInputStream ois = new ObjectInputStream(bis);
			T t = (T) ois.readObject();
			ois.close();
			bis.close();
			bos.close();
			return t;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Request deserializeRequest(byte[] data) {
		return deserialize(data);
	}

	@Override
	public Response deserializeResponse(byte[] data) {
		return deserialize(data);
	}

	@Override
	public <T extends Serializable> byte[] serialize(T object) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(object);
			oos.flush();
			oos.close();
			bos.close();
			byte[] result = bos.toByteArray();
			log.trace("Serialized: " + result.length + "|"
					+ JarmiUtil.toString(result));
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
